﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Text.RegularExpressions;

namespace TEL.ClientClasses
{
    public enum LogType
    {
        Message,
        Info,
        Warring,
        Error,
        RTP
    }
    public class SimplePhoneLog
    {
        private const string FileName = "SimplePhoneLog__{0:yyyy_MM_dd hh_mm_ss}.txt";
        private string m_fullFileName = "SimplePhoneLog.txt";

        private int MaxLenLog = 3000;
        private string FormatLog = "{0:yyyy.MM.dd HH:mm:ss}\t{1}\t\t({2})";
        private string FormatError = "{0:yyyy.MM.dd HH:mm:ss}  ОШИБКА  {1}\t\t({2})";
        public SimplePhoneLog()
        {
            string localDir = Path.Combine("SimplePhone", "log");
            localDir = Path.Combine(
                    Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),
                    localDir);
            DirectoryInfo destdir = new DirectoryInfo(localDir);
            if (!destdir.Exists)
            {
                destdir.Create();
            }
            m_fullFileName = Path.Combine(localDir, string.Format(FileName, DateTime.Now));
            if (File.Exists(m_fullFileName)) File.Delete(m_fullFileName);
        }

        public void Write(LogType logType, string info, string message)
        {
            message = Regex.Replace(message, "\r\n", "\r\n\t\t\t\t\t");
            lock (m_fullFileName)
            {
                using (StreamWriter st = new StreamWriter(m_fullFileName, true, Encoding.UTF8))
                {
                    switch (logType)
                    {
                        case LogType.Error:
                            st.WriteLine(string.Format(FormatError, DateTime.Now, info, message));
                            break;
                        default:
                            st.WriteLine(string.Format(FormatLog, DateTime.Now, info, message));
                            break;
                    }

                }
            }
        }

        public void WriteEvent (object sender, LogEventArgs e)
        {
            Write(e.LogType,e.Info,e.Message);
        }
    }
}
